<template>
  <el-dialog :visible.sync="isShow" append-to-body>
    <el-form ref="form" :model="fields" :rules="rules" label-width="80px" />
    <Parser
      v-if="formConf.fields.length > 0"
      :key="keys"
      :form-conf="formConf"
      @submit="submitForm"
    />
  </el-dialog>
</template>

<script>
import { get } from '@/api/form'
import { saveOrUpdate } from '@/api/groupdata'
import Parser from '@/components/FormGenerator/components/parser/Parser'
export default {
  components: { Parser },
  props: {
    value: {
      type: Object,
      default: () => Object.create({})
    }
  },
  data() {
    return {
      keys: +new Date(),
      formConf: { fields: [] },
      isShow: true,
      fields: {},
      rules: {},
      editData: {}
    }
  },
  watch: {
    isShow: function() {
      this.$emit('input', null)
    }
  },
  created() {
    this.getData(this.value.formId || null)
  },
  methods: {
    onOkBtnClick() {
      this.submitForm()
    },
    submitForm(formValue) {
      const _pram = this.buildFormPram(formValue)
      if (this.value.id) {
        _pram.id = this.value.id
      }
      this.$refs['form'].validate((valid) => {
        valid &&
          saveOrUpdate(_pram)
            .then(() => {
              this.isShow = false
              this.$emit('refData')
            }).catch(() => {})
      })
    },
    resetForm() {
      this.$refs['form'].resetFields()
    },
    async getData(id) {
      await get(id).then(data => {
        this.formConf = JSON.parse(data.content)
        setTimeout(() => {
          this.handlerInitEditData()
        }, 200)
      })
    },
    handlerInitEditData() {
      // this.fields = this.value
      // 回填数据
      this.fillFormData(this.formConf, this.value)
      // 更新表单
      this.keys = +new Date()
    },
    fillFormData(form, data) {
      form.fields.forEach(item => {
        const val = data[item.__vModel__]
        if (val) {
          item.__config__.defaultValue = val
        }
      })
    },
    buildFormPram(formValue) {
      const _pram = {
        gid: this.value.gid,
        type: this.value.type,
        form: {
          fields: [],
          id: this.value.formId
        }}
      const _fields = []
      Object.keys(formValue).forEach((key) => {
        _fields.push({
          name: key,
          title: key,
          value: formValue[key]
        })
      })
      _pram.form.fields = _fields
      return _pram
    }
  }
}
</script>
